/*
 * Anemometer.c
 *
 * Created: 17/02/2012 14:22:49
 *  Author: Dani
 * 
 * External clock : PB0
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>

int counter;

ISR (TIMER1_OVF_vect)
{
	counter = TCNT0;
	//Reload counter in Timer 0
	TCNT0 = 0;
	// Reload Timer1 to 1 second to next overflow
	TCNT1 = 65536-3600;
}

void InitTimer0()
{	
	// ---- Anemometer pulses counter ---
	//External clock falling edge.
	//Normal Mode
	TCCR0 = 0b00000110;
	TCNT0=0;
}

void InitTimer1()
{
  // Normal mode, no waveform generation
  TCCR1A = 0b00000000;
  // Normal mode, clock prescaler PS = 1024
  TCCR1B = 0b00000101;
  // 1 second to next overflow:
  // 3686400/1024/3600 = 1
  TCNT1 = 65536-3600;
  // Enable Timer1 overflow interrupt
  TIMSK |= 0b00000100;
}

void Anemometer_Init()
{
	InitTimer0();
	InitTimer1();
}

int Anemometer_Read() // Km/h
{
	/*Consensus Transfer Function: 
		Scale Factor (Slope): 0.765 m/s/Hz (1.711 mph/Hz; 2,754 Km/h/Hz)
		Offset: 0.35 m/s (1,26 Km/h)*/
	return (counter * 2.754 + 1.26);	
}